<?php

namespace App\Jobs\QiPao;

use App\Jobs\Job;
use App\Repositories\Group\GroupUserMatchRecordRepository;
use App\Services\Tools\PushService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ChatRecordJob extends Job
{

    protected $fromUserId;
    protected $toUserId;
    protected $chatData;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($fromUserId, $toUserId, $chatData)
    {
        $this->fromUserId = $fromUserId;
        $this->toUserId   = $toUserId;
        $this->chatData   = $chatData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('私聊统计：' . ($this->fromUserId));

        try {
            GroupUserMatchRecordRepository::getInstance()->updateData(['user_id' => $this->fromUserId, 'match_user_id' => $this->toUserId],
                ['chat_count' => DB::raw('chat_count + 1')]);

            //计算解锁进度
            $userList       = GroupUserMatchRecordRepository::getInstance()->getMatchUserData($this->fromUserId, $this->toUserId);
            $progress       = 0;
            $overCount = 0;
            foreach ($userList as $user) {
                $chatCount      = $user['chat_count'] * 5;
                $progress       += $chatCount > 50 ? 50 : $chatCount;
                if($progress >= 100){
                    $overCount++;
                }
            }

            //给双方发送进度推送
            if ($overCount <= 10) {
                (new PushService())->groupMatchSend($this->fromUserId, $this->toUserId, $progress);
                (new PushService())->groupMatchSend($this->toUserId, $this->fromUserId, $progress);
            }
        } catch (\Exception $e) {
            Log::error('私聊统计错误：' . $e->getMessage());
        }
    }
}
